package net.fdukedom.o3i.icq;

import java.io.IOException;
import java.io.OutputStream;
import net.fdukedom.o3i.util.NumberUtil;

/**
 * This is utility class to Write FLAP entries from the stream. 
 * 
 * @author duke
 */
public class FlapWriter {

    /**
     * Stream to write FLAPs to.
     */
    private OutputStream stream;

    public FlapWriter(OutputStream stream) {
        this.stream = stream;
    }
    
    /**
     * Writes flap to the stream.
     * 
     * @param flap flap to be written
     * 
     * @throws java.io.IOException if an error occured
     */
    public void write(Flap flap) throws IOException {
        byte[] flapHeaders = new byte[Flap.HEADERS_SIZE];
        flapHeaders[FlapByteOrder.COMMAND_START.getPosition()] = Flap.COMMAND_START;
        flapHeaders[FlapByteOrder.CHANNEL_ID_BYTE.getPosition()] = flap.getChannelId();
        byte[] sequenceNumberBytes = NumberUtil.convertToByteArray(flap.getSequenceNumber());
        flapHeaders[FlapByteOrder.SEQUENCE_NUMBER_START_BYTE.getPosition()] = sequenceNumberBytes[0];
        flapHeaders[FlapByteOrder.SEQUENCE_NUMBER_START_BYTE.getPosition() + 1] = sequenceNumberBytes[1];
        byte[] dataLengthBytes = NumberUtil.convertToByteArray((short) flap.getData().length);
        flapHeaders[FlapByteOrder.DATA_LENGTH_START_BYTE.getPosition()] = dataLengthBytes[0];
        flapHeaders[FlapByteOrder.DATA_LENGTH_START_BYTE.getPosition() + 1] = dataLengthBytes[1];
        stream.write(flapHeaders);
        if (flap.containsSnac()) {
            //Call to Snac writer
        } else {
            //contains raw data
            stream.write(flap.getData());
        }
        
        
    }
    
    /**
     * Closes output stream.
     * 
     * @throws java.io.IOException if an error occured
     */
    public void close() throws IOException {
        stream.close();
    }
}
